<template>
    <div class="home">
        <filterCom id="select-box" @sendForm="onHandleForm" />
        <div class="task-wrap" :style="{ '--select-heght': selectHeight }">
            <div class="task-detail">
                <div class="time">截至{{ dayjs().format("YYYY年MM月DD日") }}推进情况</div>
                <div class="total">总计: {{ total }}条</div>
            </div>
            <div class="task-tab">
                <div class="tab-item" @click="changeTab(item)"
                    :class="[currentTab == item.name + item.name2 ? 'task-active' : '']"
                    v-for="(item, index) in tabList" :key="index">
                    <div class="name">
                        {{ item.name }}
                    </div>
                    <div class="name2">
                        {{ item.name2 }}
                    </div>
                </div>
            </div>
            <btnGroup @sendOp="onHandleOp"> </btnGroup>
            <div class="task-list">
                <div class="task-header">
                    <div class="index">序号</div>
                    <div class="taskContent">具体工作内容</div>
                    <div class="process">进度状态</div>
                </div>
                <div class="task-body" id="tackBody" :style="{ '--select-heght': selectHeight }">
                    <div class="loading-wrap" v-if="loading">
                        <van-loading color="#1989fa">
                            加载中...
                        </van-loading>
                    </div>
                    <div class="task-body-wrap" v-else>
                        <div class="task-box" v-if="tableList.length > 0" v-for="(item, index) in tableList"
                            :key="item.id">
                            <div class="task-tr" @click="showMore(item, index)">
                                <div class="index">
                                    <div class="check" @click.stop="onCheckRow(item, index)"
                                        :class="[item.objectId == onCheckId ? 'checkedBox' : 'checkBox']">
                                        <img v-if="item.objectId == onCheckId" :src="checked" alt="">
                                    </div>
                                    <div class="rowIndex">
                                        {{ index + 1 }}
                                    </div>
                                    <div class="more" @click="showMore(item, index)">
                                        <img :src="item.open ? upArrow : downArrow" alt="">
                                    </div>
                                </div>
                                <div class="taskContent">{{ item.workContent }}</div>
                                <div class="process" :class="[index == 0 ? '' : 'flexCenter']">
                                    <div :class="[statusMap[item.workStatus ?? '正常'].className]" class="iconSize"></div>

                                    <div v-if="item.isDuBan == 1" style="margin-left: 3px;" class="dub iconSize"
                                        @click.stop="onHandleDuban(item)"></div>
                                    <!-- {{ statusMap[item.status].text }} -->
                                </div>
                            </div>
                            <div class="more-content" v-show="item.open">
                                <!-- 业务类型 分管部门 分管领导 -->
                                <div class="detail-top">
                                    <div class="more-row1">
                                        <div class="base-label">业务类别：</div> {{ item.businessType }}
                                    </div>
                                    <div class="more-row1">
                                        <div class="base-label">主要责任单位：</div> {{ handleOrgText(item) }}
                                    </div>
                                    <div class="more-row1">
                                        <div class="base-label">相关责任单位：</div> {{ handleOrgText2(item) }}
                                    </div>
                                    <div class="more-row1">
                                        <div class="base-label">分管领导：</div> {{ handleLdText(item.workLeader) }}
                                    </div>
                                </div>
                                <!-- 底部各个计划的时间以及集合 -->
                                <div class="detail-bottom">
                                    <div class="task-item" v-for="(task, tIndex) in item.workStep" :key="tIndex">
                                        <!-- 任务步骤标题 以及时间 -->
                                        <div class="taskStep-top">
                                            <div class="title">{{ task.title }}</div>
                                            <!-- 人名和时间 -->
                                            <div class="tAp">
                                                <div class="people">{{ task.worker }}</div>
                                                <div class="time">{{ task.time }}</div>
                                            </div>
                                        </div>
                                        <!-- 具体内容 -->
                                        <div class="taskStep-content">
                                            {{ task.content ?? '无' }}
                                        </div>

                                    </div>
                                </div>
                            </div>
                            <div class="line"></div>
                        </div>
                        <van-empty :image-size="[120, 120]" v-else description="暂无数据" />
                    </div>

                    <!-- <pagination></pagination> -->
                </div>
                <van-pagination v-if="tableList.length > 0" v-model="params.pageNo" :total-items="total"
                    :items-per-page="params.pageSize" @change="changePageSize" />
            </div>
        </div>
    </div>
</template>

<script setup>
import filterCom from "./components/filterCom.vue"
import btnGroup from "./components/btnGroup.vue";
import checked from "@/assets/images/checked.png"
import downArrow from "@/assets/images/downArrow.png"
import upArrow from "@/assets/images/upArrow.png"
import { workProgress, workAdd, draftPage } from "@/service/yearWork"
import dayjs from "dayjs"
import { showConfirmDialog } from 'vant';
import { isFirstCharChinese } from "@/utils/tool"
import { useDict } from "@/stores/dictStore"
import { useUser } from "@/stores/user"
const userStore = useUser()

const dictStore = useDict()

const { userLdList, orgList } = toRefs(dictStore)

// 处理主要责任单位
function handleOrgText(row) {
    const { mainBusinessUnitOrgCode } = row
    if (mainBusinessUnitOrgCode) {
        let arr = mainBusinessUnitOrgCode.split(',')
        let nameArr = []
        arr.forEach(item => {
            let target = orgList.value.find(org => org.code == item)
            if (target) {
                nameArr.push(target.name)
            }
        })
        return nameArr.join(',')
    } else {
        return row.businessUnit
    }

}
//处理相关责任单位
function handleOrgText2(row) {
    const { businessUnitOrgCodes } = row
    if (businessUnitOrgCodes) {
        let arr = businessUnitOrgCodes.split(',')
        let nameArr = []
        arr.forEach(item => {
            let target = orgList.value.find(org => org.code == item)
            if (target) {
                nameArr.push(target.name)
            }
        })
        return nameArr.join(',')
    } else {
        return row.businessUnit
    }
}

// 处理分管领导的数据
function handleLdText(text) {
    if (!text) {
        return ""
    }
    if (isFirstCharChinese(text)) {
        return text
    }
    let arr = text.split(',')
    let nameArr = []
    arr.forEach(item => {
        let name = userLdList.value.find(user => user.objectid == item)
        if (name) {
            nameArr.push(name.userName)
        }
    })
    return nameArr.join(',')
}


let currentTab = ref("年度重点工作推进")
function changeTab(item) {
    params.pageNo = 1
    currentTab.value = item.name + item.name2
    params.workBigType = currentTab.value
    getWorkProgress()
}


let tabList = [{
    id: 1,
    name: "年度重点工作",
    name2: "推进"
},
{
    id: 2,
    name: "环保督察问题",
    name2: "整改工作推进"
},
{
    id: 2,
    name: "近期重要工作",
    name2: "推进"
}
]

const statusMap = {
    '正常': {
        className: 'green',
        text: '绿'
    },
    '滞后': {
        className: 'yellow',
        text: '黄'
    },
    '停滞': {
        className: 'red',
        text: '红'
    },
    '完成': {
        className: 'finished',
        text: '红'
    }
}

const tableList = ref([])

let params = reactive({
    pageSize: 8,
    pageNo: 1,
    workYear: "2025",
    isDeleted: 0,
    workBigType: "年度重点工作推进"
})
const filterParams = ref({})

function changePageSize() {
    getWorkProgress()
}
const total = ref(0)
let loading = ref(true)
function getWorkProgress() {
    loading.value = true
    let requestParams = {
        ...params,
        ...filterParams.value
    }
    workProgress(requestParams).then(res => {
        total.value = res.data.total
        let list = res.data.records
        list.forEach((item, index) => {
            let workStep = [
                {
                    id: index + '-1',
                    title: '年度计划进度：',
                    worker: "",
                    time: "",
                    content: item.annualPlan
                },
                {
                    id: index + '-2',
                    title: '推进完成情况：',
                    worker: "",
                    time: "",
                    content: item.workProgress
                },
                {
                    id: index + '-3',
                    title: '需要说明事项：',
                    worker: '',
                    time: '',
                    content: item.workStatement
                },
                {
                    id: index + '-4',
                    title: '备注：',
                    worker: '',
                    time: '',
                    content: item.workNote
                }
            ]
            if (item.superviseComment) {
                workStep.push({
                    id: index + '-5',
                    title: '督办意见：',
                    worker: "",
                    time: "",
                    content: item.superviseComment
                })
            }
            item.workStep = workStep
        })
        tableList.value = list
        loading.value = false
    })
}
const onCheckId = ref(null)
const currenRow = ref(null)
// 点击勾选
function onCheckRow(item, index) {
    // 反选
    if (onCheckId.value && onCheckId.value == item.objectId) {
        onCheckId.value = null
        return
    }
    onCheckId.value = item.objectId
    currenRow.value = item
}
// 点击查看更多
function showMore(item, index) {
    tableList.value[index].open = !tableList.value[index].open
}

const routeMap = {
    '新增': '/addOrEdit',
    '修改': '/addOrEdit',
    '计划进度': '/updateTask',
    '完成情况': '/updateFinished',
    '说明事项': '/updateExplain',
    '备注': '/updateRemark',
    '历史记录变更': '/history',
    '督办': '/supHandle',
    '考核评价': '/khpjHandle',
}
const router = useRouter()
function onHandleOp(item) {
    if (item != '新增' && !onCheckId.value) {
        showToast("请选择一条数据！");
        return
    }
    if (item == '督办') {
        if (!currenRow.value.workLeader.split(',').includes(userStore.userInfo.userId)) {
            showToast("该用户对该数据暂无操作权限");
        } else {
            router.push({
                path: routeMap[item],
                query: {
                    rowData: JSON.stringify(currenRow.value)
                }
            })
        }
    }
    if (item == '历史记录变更') {
        router.push({
            path: routeMap[item],
            query: {
                rowData: JSON.stringify(currenRow.value),
                type: item == '修改' ? "edit" : "update"
            }
        })
    }
    if (item == '考核评价') {
        router.push({
            path: routeMap[item],
            query: {
                rowData: JSON.stringify(currenRow.value)
            }
        })
    }
    // if (item != '新增' && !onCheckId.value) {
    //     showToast("请选择一条数据！");
    //     return
    // }
    // if (item == '新增') {
    //     router.push({
    //         path: routeMap[item]
    //     })
    // } else if (item == '删除') {
    //     let params = {
    //         requestType: "删除",
    //         changeContentBefore: null,
    //         changeContentAfter: currenRow.value,
    //         workProgressObjectId: currenRow.value.objectId
    //     }
    //     showConfirmDialog({
    //         message:
    //             '删除该条数据需要提交审核,是否进行删除?',
    //     }).then(() => {
    //         workAdd(params).then(res => {
    //             if (res.code == 0) {
    //                 showToast("提交审核成功，请等待审核");
    //             }
    //         })
    //     })
    // } else {
    //     let draftParams = {
    //         applicantId: userStore.userInfo.userId,
    //         relatedWorkId: currenRow.value.objectId,//当前数据的id就是草稿箱关联的relatedWorkId
    //         pageNo: 1,
    //         pageSize: -1,
    //         deleteFlag: 0,
    //         draftStatus: "草稿"
    //     }
    //     draftPage(draftParams).then(res => {
    //         if (res.code == 0 && res.data.records.length > 0) {
    //             showConfirmDialog({
    //                 message: '该工作记录已经存在草稿箱中，是否跳转到草稿箱',
    //             }).then(() => {
    //                 router.push({
    //                     path: '/cgx'
    //                 })
    //             })

    //         } else {
    //             router.push({
    //                 path: routeMap[item],
    //                 query: {
    //                     rowData: JSON.stringify(currenRow.value),
    //                     type: item == '修改' ? "edit" : "update"
    //                 }
    //             })
    //         }
    //     })
    // }
}

function onHandleForm(filter) {
    params.pageNo = 1
    for (let key in filter) {
        if (filter[key] == '') {
            delete filter[key]
        }
    }
    filterParams.value = filter
    getWorkProgress()
}

function onHandleDuban(item) {
    router.push({
        path: '/dubhistory',
        query: {
            rowData: JSON.stringify(item)
        }
    })
}

const selectHeight = ref("270")
onMounted(() => {
    getWorkProgress()
})
// function setHeight() {
//     selectHeight.value = (document.getElementById("select-box").offsetHeight) / getComputedStyle(document.documentElement).fontSize.split('p')[0] + 'rem'
// }
// onMounted(() => {
//     window.addEventListener("resize",setHeight )
//     setHeight()
// })


</script>
<style lang="scss" scoped>
.home {

    .task-wrap {
        height: calc(100vh - 92px - 276px);
        padding: 31px 26px;
        box-sizing: border-box;
        box-shadow: 0px -4px 10px 4px rgba(218, 231, 245, 0.5);
        // margin-top: 5px;
        background: rgba(255, 255, 255, 1);

        .task-detail {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .time {
                font-size: 26px;
                color: rgba(128, 128, 128, 1)
            }

            .total {
                font-size: 26px;
                color: rgba(51, 51, 51, 1)
            }
        }

        .task-list {
            color: rgba(51, 51, 51, 1);

            .task-header {
                display: flex;
                justify-content: space-between;
                font-size: 26px;
                color: rgba(166, 166, 166, 1);
                text-align: center;
                vertical-align: middle;

                .index {
                    width: 15%;
                }

                .taskContent {
                    width: 65%;
                }

                .process {
                    width: 18%;
                }
            }

            // var(--select-heght)
            .task-body {
                height: calc(100vh - 92px - 276px - 31px - 21px - 112px - 40px - 60px - 102px - 80px - 98px);
                overflow-y: scroll;
                margin-top: 10px;

                .task-body-wrap {
                    height: calc(100% - 40px);
                    overflow-y: scroll;

                    .task-box {

                        .task-tr {
                            display: flex;
                            justify-content: space-between;
                            font-size: 26px;

                            .index {
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                width: 15%;
                                font-size: 26px;

                                .checkBox {
                                    border: 1px solid rgba(229, 229, 229, 1);
                                }

                                .checkedBox {
                                    border: 1px solid rgba(50, 172, 237, 1);
                                }

                                .check {
                                    display: flex;
                                    align-items: center;
                                    justify-content: center;
                                    width: 28px;
                                    height: 28px;
                                    border-radius: 2px;

                                    img {
                                        width: 18px;
                                        height: 14px;
                                    }
                                }

                                .rowIndex {
                                    margin: 0 15px;
                                }

                                .more {
                                    img {
                                        margin-bottom: 5px;
                                        width: 12px;
                                        height: 6px;

                                    }
                                }
                            }

                            .taskContent {
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                width: 63%;
                                // display: -webkit-box;
                                // -webkit-line-clamp: 2; /* 限制为3行 */
                                // -webkit-box-orient: vertical;
                                // overflow: hidden;
                                // text-overflow: ellipsis;
                            }

                            .process {
                                display: flex;
                                align-items: center;
                                justify-content: space-around;
                                width: 15%;
                            }
                        }

                        .more-content {
                            padding-left: 35px;
                            box-sizing: border-box;

                            .detail-top {
                                display: flex;
                                flex-wrap: wrap;

                                /* 允许换行 */
                                .more-row1 {
                                    margin-bottom: 12px;
                                    flex: 1 0 33.333%;
                                    display: flex;
                                    flex-wrap: wrap;
                                    font-size: 26px;

                                    .base-label {
                                        color: rgba(168, 168, 168, 1);
                                    }
                                }

                                /* 当宽度小于 600px 时，每个 item 占满整行 */
                                @media (max-width: 750px) {
                                    .more-row1 {
                                        flex: 1 0 100%;
                                        /* 每个 item 占满一整行 */
                                    }
                                }
                            }

                            .detail-bottom {

                                .taskStep-top {
                                    display: flex;
                                    align-items: center;
                                    justify-content: space-between;
                                    font-size: 26px;

                                    .title {
                                        color: rgba(168, 168, 168, 1);
                                    }

                                    .tAp {
                                        display: flex;
                                        align-items: center;
                                        font-size: 24px;
                                        color: rgba(49, 174, 254, 1);

                                        .time {
                                            display: flex;
                                            padding: 0 14px;
                                            margin-left: 20px;
                                            align-items: center;
                                            justify-self: center;
                                            border-radius: 34px;
                                            background: rgba(49, 174, 254, 0.2);

                                        }
                                    }
                                }

                                .taskStep-content {
                                    margin: 15px 0;
                                    font-size: 26px;
                                    overflow: hidden;
                                }
                            }
                        }

                        .line {
                            margin: 10px 0;
                            background: rgba(239, 239, 239, 1);
                            height: 2px;
                        }
                    }
                }

                .loading-wrap {
                    height: 100%;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }

            }
        }
    }
}

.iconSize {
    width: 32px;
    height: 40px;
}

.finished {
    background-image: url('@/assets/images/finished.png');
    background-size: 100% 100%;
}

.green {
    background-image: url('@/assets/images/process_green.png');
    background-size: 100% 100%;
}

.red {
    background-image: url('@/assets/images/process_red.png');
    background-size: 100% 100%;
}

.yellow {
    background-image: url('@/assets/images/process_yellow.png');
    background-size: 100% 100%;
}

.dub {
    background-image: url('@/assets/images/dub.png');
    background-size: 100% 100%;
}

.task-tab {
    margin-top: 10px;
    background: linear-gradient(to bottom, rgba(207, 232, 255, 1) 20%, transparent 100%);
    border-radius: 30px;
    height: 96px;
    display: flex;
    // padding: 5px;

    .tab-item {
        //   margin: 0 auto;
        font-size: 26px;
        text-align: center;
        word-wrap: break-word;
        flex: 1;
        color: rgba(102, 160, 189, 1);

        .name {
            margin-top: 5px;
        }
    }

}



.task-active {
    position: relative;
    background-image: url("@/assets/images/tabActive.png");
    background-size: 100% 100%;
    transition: all 0.3s ease-in-out;
}

.task-active::after {
    position: absolute;
    content: "";
    width: 54px;
    height: 6px;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 10px;
    background: rgba(3, 165, 253, 1);

}

.flexCenter {
    display: flex !important;
    justify-content: center !important;
}

@media (min-width: 750px) {
    .task-wrap {
        height: calc(100vh - 150px - 132px) !important;
    }

    .task-body {
        height: calc(100vh - 550px - 106px - 80px) !important;
    }
}
</style>